import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName ZKNodeOperator
 * @Description TODO
 * @Author BossZ
 * @Version 1.0
 * @Date 2019/1/15-18:26
 **/
public class ZKNodeOperator {

    private ZooKeeper zooKeeper;

    public static final Logger log  = LoggerFactory.getLogger(ZKNodeOperator.class);
    public ZKNodeOperator() {
    }

    public ZKNodeOperator(String connectString) {
        try {
            zooKeeper = new ZooKeeper(connectString,200,(e)->{
                log.info("-----"+e.getState().name());
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void createZKnode(String path, byte[] data, List<ACL> acls){
        String result = "";
        /**
         * 同步或异步创建节点，都不支持子节点的递归创建，异步有个callback函数
         * 参数：
         * path:
         * data:
         * acl:控制权限
         * createMode:节点类型，是一个枚举
         *     PERSISTENT:持久节点
         *     PERSISTENT_SEQUENTIAL:持久顺序节点
         *     EPHEMERAL:临时节点
         *     EPHEMERAL_SEQUENTIAL:临时顺序节点
         */
        try {

//            result = zooKeeper.create(path,data,acls, CreateMode.EPHEMERAL);
//            System.out.println("创建临时节点：\t"+result+"\t成功.....");

            String ctx ="{'create':'success'}";
            zooKeeper.create(path,data,acls,CreateMode.PERSISTENT,new CreateCallBack(),ctx);
            TimeUnit.SECONDS.sleep(2);
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    public static void main(String[] args) throws Exception{
        ZKNodeOperator znode = new ZKNodeOperator(Main.zkServerPath);
//        znode.createZKnode("/testnode","testnode".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE);
//        Stat stat = znode.getZooKeeper().setData("/testnode", "xyz".getBytes(), 0);
//        System.out.println(stat.getAversion());

        znode.getZooKeeper().delete("/testnode",1);

    }

    public ZooKeeper getZooKeeper() {
        return zooKeeper;
    }

    public void setZooKeeper(ZooKeeper zooKeeper) {
        this.zooKeeper = zooKeeper;
    }
}
